"ui";
ui.layout(
        <vertical>
            <appbar>
                <toolbar id="toolbar" title="自动办证"/>
                <tabs id="tabs"/>
            </appbar>
            <viewpager id="viewpager">
                <vertical>
                    <card w="*" h="40" margin="10" cardCornerRadius="2dp"
                        cardElevation="1dp" gravity="center_vertical">
                        <text text="无障碍服务" padding="18 8 8 8" textSize="15sp" gravity="center_vertical" textColor="black"/>

                        <Switch id="autoService"  checked="{{auto.service != null}}"  text="无障碍服务"  padding="18 8 8 8" textSize="15sp"/>

                        <View bg="#4caf50" h="*" w="5"/>
                    </card>
                    <card w="*" h="150" margin="10 10 20 30"    cardCornerRadius="2dp"
                        cardElevation="1dp" gravity="center_vertical">
                        <vertical>
                            <text text="温情提示:" padding="8 8 8 8" textSize="15sp" gravity="center_vertical" textColor="black"/>
                            <text text="使用本软件前请阅读使用手册，正常使用的情况不建议频繁更新，保证稳定运行。如果哪个版本有异常或者需要适配请及时反馈，请说明具体情况，工作人员会第一时间处理！" 
                            padding="18 8 8 8" textSize="15sp" gravity="center_vertical" textColor="#808080" typeface="sans"/>

                        </vertical>
                        
                    </card>
                    <card w="*" h="40" margin="10 10 10 10"    cardCornerRadius="2dp"
                        cardElevation="1dp" gravity="center_vertical">
                        <horizontal>
                            <text text="证件类型" padding="18 8 8 8" textSize="15sp" gravity="center_vertical" textColor="black"/>
                            
                            <spinner id="sp1" entries="自动办证（六环外）|自动办证（六环内）" textColor="black" marginLeft="20"/>
                        </horizontal>
                        <View bg="#4caf50" h="*" w="5"/>
                    </card>

                    <card w="*" h="40" margin="10 10 10 10"    cardCornerRadius="2dp"
                        cardElevation="1dp" gravity="center_vertical">
                        <horizontal>
                            <text text="自动续办" padding="18 8 8 8" textSize="15sp" gravity="center_vertical" textColor="black"/>
                            
                            <spinner id="sp2" entries="不自动续办|每周一|每周二|每周三|每周四|每周五|每周六|每周日" textColor="black" marginLeft="20"/>
                        </horizontal>
                        <View bg="#4caf50" h="*" w="5"/>
                    </card>

                

                    <card w="*" h="40" margin="10 5 10 30"    cardCornerRadius="2dp"
                        cardElevation="1dp" gravity="center_vertical">
                          <horizontal>
                            <text text="激活状态：" padding="18 8 8 8" textSize="15sp" gravity="center_vertical" textColor="black"/>
                            <text id="activeStatus" text="未激活" padding="18 8 8 8" textSize="15sp" gravity="center_vertical" textColor="#808080"/>
                            <text id="isxvban" text="" padding="18 8 8 8" textSize="15sp" gravity="center_vertical" textColor="#808080"/>

                        </horizontal>   
                    </card>

                    <button id="autoenroll" text="设置自动续办" style="Widget.AppCompat.Button.Colored" w="*" margin="10" />

                   
                    <button id="runenroll" text="单次自动办理" style="Widget.AppCompat.Button.Colored" w="*" margin="10" />


                </vertical>

            </viewpager>
          

        </vertical>
);

var scriptStatus = false;
let base_url = "http://114.115.131.52:8010/";
// let base_url = "http://192.168.1.4:8010/";

let miyao ="66c5272f1f049cadea2d968d1226fadf";
let salt ="zuogerenba"
//初始化函数
function init(){
    check();
    changeTag();
   
    //反显设置
    let stora = storages.create('enter_permit_storge');
    let sp1 =stora.get("type");
    let sp2 =stora.get("autoDay");
    let isAuto = stora.get("isAuto")
    if(sp1 != undefined){
        ui.sp1.setSelection(sp1)
    }
    if(sp2 != undefined){
        ui.sp2.setSelection(sp2)
    }
    if(isAuto == undefined || isAuto == 0){
        ui.autoenroll.setText("设置自动续办")
    }else{
        ui.autoenroll.setText("取消续办")
    }

    //判断时间开始自动续办
    let week = getWeek();
    if(isAuto == 1 && week ==sp2){
        let isRunKey = "is"+getTime();
        let isRun = stora.get(isRunKey);
        if(isRun != 1){
            stora.put(isRunKey,1);

            threads.start(function(){
                enroll();
            })

        }
        if(isRun ==1){
            ui.isxvban.setText("今日已自动续办")

        }
        
        
    }
    //后台检测天数
     var thread = threads.start(function(){
        renew()
    })
    //主线程执行
    var changeTagid = setInterval(function(){
        if(scriptStatus == true){
            changeTag();
        }
    }, 1000);

    setTimeout(function(){
        clearInterval(changeTagid);
    }, 5000);
    
}
init();
//后台验证,验证激活码是否到期
function renew(){
    let stor = storages.create('enter_permit_storge');
    let  cdkey = stor.get("cdkey");
    let  sign = stor.get("sign");
    let  token = stor.get("token");
    
    let res = http.postJson(base_url+"device/renew",{
        cdkey:cdkey,
        sign:sign,
        token:token
    });
    let json = res.body.json()
    log(json)

    //系统异常
    if(json.code != 200){
        toast("出现错误~请联系管理员")
    }else{
        if(json['data'].code !=200){
            toast(json['data'].msg)
        }else{
            let stora = storages.create('enter_permit_storge');
            stora.put("usable",json['data'].usable)
            stora.put("days",json['data'].days)
            log(json['data'])

            check();
           
        }

    }

}
//前台验证
function check(){
    let stor = storages.create('enter_permit_storge');
    let  cdkey = stor.get("cdkey");
    let  sign = stor.get("sign");
    let  token = stor.get("token");
    let  days = stor.get("days");

    if(cdkey != undefined && sign != undefined && token != undefined && validateCode(sign,cdkey) == 1 && days !=0){
        scriptStatus = true;

    }else{
        scriptStatus = false;
    }

    
}
//更改激活标识
function changeTag(){
    let stora = storages.create('enter_permit_storge');
    let usable =stora.get("usable");

    if(scriptStatus == true){
        ui.activeStatus.setText(usable)
        ui.activeStatus.attr("textColor","#ff6b6b")

    }

}
//设置自动续办时间
ui.autoenroll.on("click", () => {
    check()
    if(scriptStatus == true){
        let stor = storages.create('enter_permit_storge');
        let sp2 = ui.sp2.getSelectedItemPosition()
        let isAuto = stor.get("isAuto")
        log(isAuto)
        //设置自动
        if(isAuto == undefined || isAuto == 0){
            confirm("确认开启吗","温情提示：使用前请阅读使用手册").then(value=>{
                if(value == true){
                    stor.put("autoDay",sp2)
                    stor.put("isAuto",1)
                    ui.autoenroll.setText("取消续班")
                }
            });
        }else{
            confirm("确认关闭吗","关闭后将无法自动续办").then(value=>{
                if(value == true){
                    stor.put("autoDay",sp2)
                    stor.put("isAuto",0)
                    ui.autoenroll.setText("设置自动续办")
                }
            });
        }
        isAuto = stor.get("isAuto")
        log(isAuto)

    }else{
        rawInput("请输入激活码","").then(cdkey =>{
            if(cdkey == ''){
                toast("请输入激活码，需要先激活哦~")
            }else{
                //激活
                var thread = threads.start(function(){
                    active(cdkey)
                })

                //主线程执行
                var setTextid = setInterval(function(){
                    if(scriptStatus == true){
                        changeTag();
                    }
                }, 1000);
                setTimeout(function(){
                    clearInterval(setTextid);
                }, 5000);
                

            }
        });
    
    }

})

//办理进京证
ui.runenroll.on("click", () => {
    check()
    if(scriptStatus == true){
        //设置证件类型
        let stor = storages.create('enter_permit_storge');
        let sp1 = ui.sp1.getSelectedItemPosition()
        stor.put("type",sp1)

        threads.start(function(){
            enroll();
        })

    }else{
        rawInput("请输入激活码","").then(cdkey =>{
            if(cdkey == ''){
                toast("请输入激活码，需要先激活哦~")
            }else{
                //激活
                var thread = threads.start(function(){
                    active(cdkey)
                })

                //主线程执行
                var setTextid = setInterval(function(){
                    if(scriptStatus == true){
                        changeTag();
                    }
                }, 1000);
                setTimeout(function(){
                    clearInterval(setTextid);
                }, 5000);
                

            }
        });
    
    }
    
})

function active(cdkey){
    let finger = device.fingerprint
    let imei = device.getIMEI()
    let mac = device.getMacAddress()
    //激活码

    let dialog = dialogs.build({
        content: "激活成功,感谢您的支持!（‐＾▽＾‐）",
        positive: "开始使用"
    }).on("positive", () => {
    });

    if(cdkey == ''){
        toast("请输入激活码，需要先激活哦~");
        return;
    }

    let res = http.postJson(base_url+"device/add",{
        fingerprint:finger,
        imei:imei,
        mac:mac,
        cdkey:cdkey
    });
    let json = res.body.json()
    //系统异常
    if(json.code != 200){
        toast("出现错误~请联系管理员")
    }else{
        if(json['data'].code !=200){
            toast(json['data'].msg)
        }else{
            let stora = storages.create('enter_permit_storge');
            stora.put("cdkey",cdkey)
            stora.put("token",json['data'].token)
            stora.put("sign",json['data'].sign)
            stora.put("usable",json['data'].usable)
            stora.put("days",json['data'].days)

            dialog.show();
            check()
        }

    }
    
}


//办理进京证
function enroll(){
    let thread = threads.start(function () {
        launch('com.zcbl.bjjj_driving')
        sleep(1500)
        text("进京证办理").findOne().parent().parent().click();
        
        //进京证办理
        sleep(1500)
        id("tv_applyJJZ").findOne().click() //申请办证
        sleep(1500)
    
        //温情提示
        id("tv_top").findOne().click()
        sleep(1500)
        id("tv_bottom").findOne().click()
        sleep(1500)
    
        //选择证件类型
        let stor = storages.create('enter_permit_storge');
        sp1 = stor.get("type")
        if(sp1 == undefined ||sp1 == 0){
            id("area_2").findOne().click()  //六环外
        }else{
            id("area_1").findOne().click() //六环内
        }

        sleep(1500)
        id("tv_next").findOne().click()
        sleep(1500)

        //人员信息
        id("tv_next").findOne().click()
        sleep(1500)

        //进京证信息
        text("进京目的（可多选）").findOne().parent().parent().child(1).child(0).click();
        text("进京目的（可多选）").findOne().parent().parent().child(1).child(2).click();

        sleep(1500)
        text("请选择进京道路").findOne().click();
        sleep(1500)
        id("tv_1").className("android.widget.TextView").text("京沪高速").findOne().parent().click()
        sleep(1500)
        id("tv_mdd").findOne().click()
        sleep(1500)

        //选择地区
        id("tv_quxian").findOne().click()
        sleep(1500)
        click(323,2222)
        sleep(1500)
        //设置详细地址
        id("et_local_detail").findOne().setText("中南海")
        sleep(1500)
        id("tv_next").findOne().click()

        sleep(1500)
        id("tv_next").findOne().click()

        //确定办理
        sleep(1500)
        id("tv_sure_submit").findOne().click()
    
    })
    thread.join();
   
}

// 将二进制数据转换成16进制字符串
function byteArrayToHexString(bytes) {
    var val = "";
    for (var i = 0; i < bytes.length; i++) {
        var tmp = bytes[i];
        if (tmp < 0) {
            tmp = 256 + tmp;
        }
        tmp = tmp.toString(16);
        if ((tmp + "").length == 1) {
            tmp = "0" + tmp;
        }
        val += tmp;
    }
    return val;
}

function md5(string) {
    var md = java.security.MessageDigest.getInstance("MD5");// 生成一个MD5加密计算摘要
    md.update(java.lang.String(string).getBytes("UTF-8"));// 计算md5函数，字符编码是 UTF-8

    return byteArrayToHexString(md.digest());
}

//验证服务器
function validateCode(sign,cdkey){

    if(sign === md5(md5(cdkey+miyao)+salt)){
        return 1;
    }else{
        //算法不一样
        return 0;
    }

}

//获取当前的时间
function getTime() {
    return new java.text.SimpleDateFormat("yyyyMMdd").format(new Date());
}

function getWeek() {
    let week = new Date().getDay(); 
    if (week == 0) {  
        week = 7;  
    }
    return week;
}

//开启无障碍服务
ui.autoService.on("check", function(checked) {
    if(checked && auto.service == null) {
        app.startActivity({
            action: "android.settings.ACCESSIBILITY_SETTINGS"
        });
    }
    if(!checked && auto.service != null){
        auto.service.disableSelf();
    }
});